#!/usr/bin/evn pyton

import os, sys

sys.path.append('/home/brenden/work/myproject/mysite/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from threading import Timer
from datetime import datetime, timedelta
import time
import logging

from polycom_checker2 import PolycomNetworkChecker
from brping import ping
from conn import MGDB
from brispone.models import Net

mon, tue, wed, thr, fri, sat, sun = range(0,7)

check_list = (
    ('micheon', (mon, (10, 10)), '125.248.148.165'), 
    ('banseong', (mon, (11, 50)), '125.248.148.124'), 
    ('soungdeok', (mon, (12, 40)), '125.248.138.53'), 
    ('yeha', (tue, (10, 0)), '61.108.15.213'), 
    ('jiphyun', (tue, (11, 50)), '125.248.148.156'), 
    ('uam', (tue, (12, 40)), '125.248.149.124'), 
    ('samcheonpo', (wed, (10, 0)), '61.108.118.245'), 
    ('jiphyun', (wed, (11, 50)), '125.248.148.156'), 
    ('chulseong', (wed, (12, 40)), '125.248.151.14'), 
    ('macheon', (thr, (10, 0)), '125.248.142.125'), 
    ('bongsoo', (thr, (11, 50)), '125.247.245.130'), 
    ('hansan', (thr, (12, 40)), '180.80.155.67'), 
    ('sudong', (fri, (15, 0)), '125.248.145.148'), 
    ('moonam', (fri, (11, 50)), '117.110.245.20'), 
    ('moonam', (fri, (12, 40)), '117.110.245.20'), 
    #('gaon', (fri, (12, 45)), '122.203.149.184'), 
)

def convert_dic(d):
    """
    "_id" : ObjectId("4eb73da9c8c0e80d07000000"),
    "max" : "343.791",
    "vj" : "30 ms",
    "aj" : "3 ms",
    "apl" : "7",
    "date" : "2011-11-07 12:08:38",
    "vpl" : "27",
    "avg" : "341.230",
    "speed" : "512 K",
    "a" : "64 K",
    "loss" : "0",
    "school" : "'IUC",
    "min" : "338.871",
    "tpl" : "34",
    "system" : "Polycom/HDX 8000 HD/Release - 2.0.3.1-2729",
    "source" : "125.248.148.165",
    "v" : "448 K",
    "type" : "H.323"
    """
    for k in d.keys():
        if k in ('max', 'apl', 'vpl', 'avg','loss', 'min', 'tpl'):
            d[k] = float(d[k])
        if k in ('vj', 'aj', 'speed', 'a','v'):
            d[k] = int(d[k].split(' ')[0])

db = MGDB('emc', 'net')

def ucheck(*l):
    print '---------------'
    d = {'school':l[0]}
    ip = l[1]

    dd = ping(ip)
    d.update(dd)
    p = PolycomNetworkChecker(ip) 
    dd = p.check()
    if dd:
        d.update(dd) 
    convert_dic(d)        
    n = Net(**d)
    n.save()
    print d

def check_6times(sname, ip):
    sec = 60 
    utime = 5
    Timer(0 * utime * sec, ucheck, (sname, ip)).start()
    Timer(1 * utime * sec, ucheck, (sname, ip)).start()
    Timer(2 * utime * sec, ucheck, (sname, ip)).start()
    Timer(3 * utime * sec, ucheck, (sname, ip)).start()
    Timer(4 * utime * sec, ucheck, (sname, ip)).start()
    Timer(5 * utime * sec, ucheck, (sname, ip)).start()
 
class AllMatch(set):
    """Universal set - match everything"""
    def __contains__(self, item): return True

allMatch = AllMatch()

def conv_to_set(obj):  # Allow single integer to be provided
    if isinstance(obj, (int,long)):
        return set([obj])  # Single item
    if not isinstance(obj, set):
        obj = set(obj)
    return obj

# The actual Event class
class Event(object):
    def __init__(self, s):
        self.mins = conv_to_set(s[1][1][1]+5)
        self.hours= conv_to_set(s[1][1][0])
        self.dow = conv_to_set(s[1][0])
        self.sname = s[0]
        self.ip = s[2]

    def matchtime(self, t):
        """Return True if this event should trigger at the specified datetime"""
        return ((t.minute in self.mins) and
                (t.hour in self.hours) and
                (t.weekday() in self.dow))

    def check(self, t):
        if self.matchtime(t):
            print 'ok'
            check_6times(self.sname, self.ip)            

class CronTab(object):
    def __init__(self, *events):
        self.events = events

    def run(self):
        while 1:
            t = datetime(*datetime.now().timetuple()[:5])
            print t
            for e in self.events:
                e.check(t)
            time.sleep(60)

#            while datetime.now() < t:
#                print (t-datetime.now()).seconds
#                time.sleep((t - datetime.now()).seconds)

if __name__ == '__main__':
    events = []
    for s in check_list:
        e = Event(s)
        events.append(e)
    c = CronTab(*events)
    c.run()
